package entity

import (
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"nspel/nspel"
	"strconv"
)

type Country struct {
	Id   int64  `orm:"pk;auto;column(id)"`
	Name string `orm:"column(name)"`
}

func (*Country) TableName() string {
	return "country"
}

func init() {
	orm.RegisterModel(new(Country))
}

func (c *Country) SelectAllByName(name string) error {
	c.Name = name
	key := "country"
	hashKey := "name[\"" + name + "\"]"
	err := nspel.RedisHgetJson(key, hashKey, c)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	err = nspel.GetOrmEngine().Read(c, "name")
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, c)
	return nil
}

func (c *Country) SelectAllById(id int64) error {
	key := "country"
	hashKey := "id[" + strconv.FormatInt(id, 10) + "]"
	err := nspel.RedisHgetJson(key, hashKey, c)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	c.Id = id
	err = nspel.GetOrmEngine().Read(c, "id")
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, c)
	return nil
}
